<?php

class ReportesController extends Model3_Controller {

    protected $_utilidad;
    protected $_costoServicio;
    protected $_costoTerceros;
    
    
    public function init() {
        $this->view->getJsManager()->addJs('jquery/bootstrap.js');
        $this->view->getJsManager()->addJs('jquery/jquery.sparkline.js');
        $this->view->getJsManager()->addJs('reportes/reportes.js');
        $this->view->getJsManager()->addJsVar('urlGetReportUtility', '"' . $this->view->url(array('module' => '', 'controller' => 'Reportes', 'action' => 'utility')) . '"');
        $this->view->getJsManager()->addJsVar('urlGetReportInvoice', '"' . $this->view->url(array('module' => '','controller' => 'Reportes', 'action' => 'invoice')) . '"');
        $this->view->getJsManager()->addJsVar('urlGetReportGain', '"' . $this->view->url(array('module' => '','controller' => 'Reportes', 'action' => 'gain')) . '"');
        $this->view->getJsManager()->addJsVar('ajaxSearchEventReport', '"' . $this->view->url(array('module' => '','controller' => 'Reportes', 'action' => 'axSearchEvent')) . '"');
        $this->view->getJsManager()->addJsVar('ajaxSearchClientReport', '"' . $this->view->url(array('module' => '','controller' => 'Reportes', 'action' => 'axSearchClient')) . '"');
        $this->view->getJsManager()->addJsVar('ajaxSearchGainReport', '"' . $this->view->url(array('module' => '','controller' => 'Reportes', 'action' => 'axSearchGain')) . '"');
    }

    public function indexAction() 
    {
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        /* @var $em Doctrine\ORM\EntityManager */
        $events = $em->getRepository('DefaultDb_Entities_Eventos')->findAll();
        $this->view->events = $events;
        
    }

    public function reportUtilityAction() 
    {
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        $idEvent = $this->getRequest()->getParam('event');
        /* @var $em Doctrine\ORM\EntityManager */
        $detallesXEvento = $em->getRepository('DefaultDb_Entities_DetalleXPaquete');
        $event = $em->find('DefaultDb_Entities_Eventos', $idEvent);
        $client = $event->getCliente();
        if($client)
        {
            $detallesDelPaquete = $detallesXEvento->findBy(array('paquete' => $event->getPaquete()->getId())); 
            $urlGraphics = $this->creaGraficaUtilidad($detallesDelPaquete);
            $this->view->urlGraphics = $urlGraphics;
            $this->view->event = $event;
            $this->view->client = $client;
            $this->view->detallesXPaquete = $detallesDelPaquete;
        }     
        else
            $this->view->error = true;
    }

    private function creaGraficaUtilidad($paquete)
    {
        $utilidad = $costoTerceros = $mayor = 0;
        foreach($paquete as $pqt)
        {
            $utilidad += ($pqt->getServicio()->getCostoCliente() - $pqt->getServicio()->getCosto());  
            $costoTerceros += $pqt->getServicio()->getCosto();
        }
               
        $GraphData = array($utilidad,$costoTerceros);
        $GraphLabel = array("Utilidad", "Costo Terceros"); 
        $fixImage = new FixImagesController();
        $urlGraphics = $fixImage->graphBarsAction($GraphData, $GraphLabel);
        return $urlGraphics;
    }
    
    public  function creaGraficaPie($facturas)
    {
        $utilidad = $iva = $mayor = 0;
        foreach($facturas as $factuta)
        {
            $utilidad += $factuta->getCosto();
            $iva += ($factuta->getCosto() * .16);
        }
               
        $GraphData = array($utilidad,$iva);
        $GraphLabel = array("Utilidad", "IVA"); 
        $fixImage = new FixImagesController();
        $urlGraphics = $fixImage->graphPieAction($GraphData, $GraphLabel);
        return $urlGraphics;
    }
        
    public function invoiceAction() 
    {
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        /* @var $em Doctrine\ORM\EntityManager */
        $facturas = $em->getRepository('DefaultDb_Entities_Facturas')->findAll();
        $this->view->facturas = $facturas;
    }

    public function reportInvoiceAction() 
    {
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        $idCliente = $this->getRequest()->getParam('client');
        /* @var $em Doctrine\ORM\EntityManager */
        $eventAdapter = $em->getRepository('DefaultDb_Entities_Eventos');
        $invoiceAdapter = $em->getRepository('DefaultDb_Entities_Facturas');

        $today = new DateTime();
        
        $event = $eventAdapter->findBy(array('cliente' => $idCliente));
        $client = $em->find('DefaultDb_Entities_Usuarios', $idCliente);

        if($event)
        {
            $invoice = $invoiceAdapter->findBy(array('evento' => $event[0]->getId()));
            if($invoice)
            {
                $this->view->eventos = $event[0];
                $this->view->factura = $invoice[0];
                $this->view->today = $today->format('d-m-Y');
            } 
        }
        else
            $this->view->error = true;
        
        $this->view->cliente = $client;
       
    }

    public function gainAction() 
    {
    }

    public function axSearchEventAction() {
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        $this->view->setUseTemplate(false);
        if ($this->getRequest()->isPost()) {
            $post = $this->getRequest()->getPost();
            $name = $post['value'];
            /* @var $em Doctrine\ORM\EntityManager */
            $eventAdapter = $em->getRepository('DefaultDb_Entities_Eventos');
            $events = $eventAdapter->getEventsByName($name);
            $this->view->events = $events;
        }
    }

    public function axSearchClientAction() {
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        $this->view->setUseTemplate(false);
        if ($this->getRequest()->isPost()) {
            $post = $this->getRequest()->getPost();
            $name = $post['value'];
            /* @var $em Doctrine\ORM\EntityManager */
            $clientAdapter = $em->getRepository('DefaultDb_Entities_Usuarios');
            $clients = $clientAdapter->getClientsByName($name);
            $this->view->clientes = $clients;
        }
    }

    public function axSearchGainAction() 
    {
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        $url = "";

        $this->view->setUseTemplate(false);
        if ($this->getRequest()->isPost()) 
        {
            $post = $this->getRequest()->getPost();
            $startDate = $post['fechaIni'];
            $endDate = $post['fechaFin'];
            /* @var $em Doctrine\ORM\EntityManager */
            $invoiceAdapter = $em->getRepository('DefaultDb_Entities_Facturas');
            $invoice = $invoiceAdapter->findBetween($startDate, $endDate);
            if($invoice)
            {
                $url = $this->creaGraficaPie($invoice);
            }
            $today = new DateTime();
            $this->view->invoice = $invoice;
            $this->view->startDate = $startDate;
            $this->view->endDate = $endDate;
            $this->view->today = $today->format('Y-m-d');
            $this->view->urlGrafica = $url;
        }
    }
    
    public function servicesAnnualAction()
    {
        $this->view->getJsManager()->addJs('reportes/serviceReport.js');
        $this->view->getJsManager()->addJsVar('axServices', '"' . $this->view->url(array('controller' => 'Reportes', 'action' => 'axServicesAnnual')) . '"');
    }
    
    public function axServicesAnnualAction()
    {
        $this->view->setUseTemplate(false);
        if($this->getRequest()->isPost())
        {
            /*@var $em Doctrine\ORM\EntityManager */
            $dbs = Model3_Registry::getInstance()->get('databases');
            $em = $dbs['DefaultDb'];
            
            $eventAdapter = $em->getRepository('DefaultDb_Entities_Eventos');
            $post = $this->getRequest()->getPost();
            $anio = $post['year'];
            
            $today = new DateTime();
            $fechaIni = new DateTime();
            $fechaFin = new DateTime();
            
            $fechaIni = $fechaIni->setDate($anio-1, 12, 31);
            $fechaFin = $fechaFin->setDate($anio+1, 1, 1);
            $fechaIni = $fechaIni->format('Y-m-d');
            $fechaFin = $fechaFin->format('Y-m-d');
            $eventosMañana = $eventAdapter->getEventMorning($fechaIni,$fechaFin);
            $eventosTarde = $eventAdapter->getEventafternoon($fechaIni,$fechaFin);
            $eventosNoche = $eventAdapter->getEventNight($fechaIni,$fechaFin);
            $totalEventos = count($eventosMañana) + count($eventosTarde) + count($eventosNoche);
            
            $graficaPie = new FixImagesController();
            $GraphData = array(count($eventosMañana),count($eventosTarde),count($eventosNoche));
            $contM=count($eventosMañana);
            $cadM="Mañana: ".$contM;
            $GraphLabel = array($cadM,"Tarde","Noche");
            $urlGrafica = $graficaPie->graphPieAction($GraphData,$GraphLabel);
           
            $this->view->rutaGrafica = $urlGrafica;
            $this->view->today = $today;
            $this->view->fechaIni = $fechaIni;
            $this->view->fechaFin = $fechaFin;
            $this->view->numEventos = $totalEventos;
            $this->view->eventosMañana = count($eventosMañana);
            $this->view->eventosTarde = count($eventosTarde);
            $this->view->eventosNoche = count($eventosNoche);
            $this->view->year = $anio;
            
        }
        
    }

    public function reservationAction()
    {
        $this->view->getJsManager()->addJs('reportes/datepickerReservation.js');
        $this->view->getJsManager()->addJsVar('axCalendar', '"' . $this->view->url(array('controller' => 'Reportes', 'action' => 'axCalendar')) . '"');
        $this->view->getCssManager()->addCss('../scripts/js/fullcalendar-1.5.1/fullcalendar/fullcalendar.css');
        $this->view->getJsManager()->addJs('fullcalendar-1.5.1/fullcalendar/fullcalendar.min.js');
        $this->view->getJsManager()->addJs('calendarInit.js');
        $this->view->getCssManager()->addCss('calendar.css');
    }

    public function axCalendarAction()
    {
        $this->view->setUseTemplate(false);
        if($this->getRequest()->isPost())
        {
            /*@var $em Doctrine\ORM\EntityManager */
            $dbs = Model3_Registry::getInstance()->get('databases');
            $em = $dbs['DefaultDb'];
            
            $eventAdapter = $em->getRepository('DefaultDb_Entities_Eventos');
            $post = $this->getRequest()->getPost();
            $fechaPost = $post['fechaIni'];
            
            $fecha = str_split($fechaPost);
            $iniciales = $fecha[0].$fecha[1].$fecha[2];
            $fechaIni = $fecha[8].$fecha[9];
//            $mes = $fecha[].$fecha[].$fecha[];
//            var_dump($fecha); die;
            switch($iniciales)
            {
                case 'Mon':
                        $fechaFin = $fechaIni + 6;
                    break;
                case 'Tue':
                        $fechaIni = $fechaIni - 1;
                        $FechaFin = $fechaIni + 5;
                    break;
                case 'Wed':
                        $fechaIni = $fechaIni - 2;
                        $FechaFin = $fechaIni + 4;
                    break;
                case 'Thu':
                        $fechaIni = $fechaIni - 3;
                        $FechaFin = $fechaIni + 3;
                    break;
                case 'Fri':
                        $fechaIni = $fechaIni - 4;
                        $FechaFin = $fechaIni + 2;
                    break;
                case 'Sat':
                        $fechaIni = $fechaIni - 5;
                        $FechaFin = $fechaIni + 1;
                    break;
                case 'Sun':
                        $fechaIni = $fechaIni - 6;
                        $FechaFin = $fechaIni + 5;
                    break;
            }
            $eventos = $eventAdapter->getEventsBetweenDate($fechaIni,$fechaFin);
            
            $this->view->fechaIni = $fechaIni;
            $this->view->fechaFin = $fechaFin;
            $this->view->eventos = $eventos;
        }
    }
    
    public function invoiceDateAction()
    {
        $this->view->getJsManager()->addJs('reportes/datepickerReservation.js');
        $this->view->getJsManager()->addJsVar('axInvoiceDate', '"' . $this->view->url(array('controller' => 'Reportes', 'action' => 'axInvoiceDate')) . '"');
    }
    
    public function axInvoiceDateAction()
    {
        $this->view->setUseTemplate(false);
        if($this->getRequest()->isPost())
        {
            /*@var $em Doctrine\ORM\EntityManager */
            $dbs = Model3_Registry::getInstance()->get('databases');
            $em = $dbs['DefaultDb'];
            
            $invoiceAdapter = $em->getRepository('DefaultDb_Entities_Facturas');
            $post = $this->getRequest()->getPost();
            $fechaIni = $post['diaIni'];
            $fechaIni = new DateTime($fechaIni);
            $fechaIni = $fechaIni->format('Y-m-d');
            $fechaFin = $post['diaFin'];
            $fechaFin = new DateTime($fechaFin);
            $fechaFin = $fechaFin->format('Y-m-d');
            $today = new DateTime();
            
            $invoices = $invoiceAdapter->findBetween($fechaIni, $fechaFin);
            $this->view->invoices = $invoices;
            $this->view->fechaIni = $fechaIni;
            $this->view->fechaFin = $fechaFin;
            $this->view->today = $today->format('d-m-Y');
        }
    }
    
    public function contactUsAction() 
    {
        $this->view->getJsManager()->addJs('jquery/jquery.validate.js');
        $this->view->getJsManager()->addJs('contactUs/contactUs.js');

        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        $event = new DefaultDb_Entities_Contacts();
        $admin = array('ayde.rod@gmail.com');

        if ($this->getRequest()->isPost()) {
            $post = $this->getRequest()->getPost();
            $event->setFirstName($post['firstName']);
            $event->setLastName($post['lastName']);
            $event->setUsername($post['username']);
            $event->setPnone($post['telephone']);
            $event->setEventName($post['eventName']);
            $event->setEventWebsite($post['eventWebsite']);
            $event->setComments($post['comments']);

            $date = new DateTime();
            $mailHelper = new Helper_MailHelper();
            foreach ($admin as $adm)
                $mailHelper->sendMailBusinessComercial($adm, $event, $post['comments'], $date);

            $em->persist($event);
            $em->flush();
        }
    }


}
